package com.hae.shop.micoshopportalweb.controller.member;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.constant.Constants;
import com.hae.shop.common.util.BeanConvertUtil;
import com.hae.shop.member.model.reqDto.UserRegistryReqDto;
import com.hae.shop.micoshopportalweb.controller.member.feign.MemberFeign;
import com.hae.shop.micoshopportalweb.controller.member.vo.RegisterReqVo;
import com.hae.shop.micoshopportalweb.utils.RandomValidateCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * 注册相关
 */
@Controller
@Slf4j
public class RegisterController {

    @Autowired
    private MemberFeign memberFeign;

    /**
     * 跳转到注册页面
     *
     * @return
     */
    @GetMapping("/register.html")
    public String getRegister() {
        return Constants.MEMBER_REGISTER_PAGE;
    }

    /**
     * 跳转到注册页面
     *
     * @return
     */
    @PostMapping("/register")
    public String postRegister(@ModelAttribute("registerReqVo") @Valid RegisterReqVo registerReqVo, BindingResult bindingResult,
                               HttpSession httpSession, Model model) {
        // 1.参数验证
        if (bindingResult.hasErrors()) {
            // 获取第一个错误!
            model.addAttribute("error",bindingResult.getFieldError().getDefaultMessage());
            return Constants.MEMBER_REGISTER_PAGE;
        }
        // 2.校对验证码
        if (!RandomValidateCodeUtil.checkVerify(registerReqVo.getGraphicCode(), httpSession)) {
            model.addAttribute("error", "图形验证码错误");
            return Constants.MEMBER_REGISTER_PAGE;
        }

        // 将VO转换DTO
        UserRegistryReqDto userRegistryReqDto = BeanConvertUtil.EToT(registerReqVo, UserRegistryReqDto.class);
        try {
            Response<Boolean> registerResponse = memberFeign.register(userRegistryReqDto, registerReqVo.getRegistCode());
            if (!registerResponse.isSuccess()) {
                model.addAttribute("error", registerResponse.getErrorMsg());
                return Constants.MEMBER_REGISTER_PAGE;
            }
        } catch (Exception e) {
            log.error(">>>>>", e);
            model.addAttribute("error", "系统出现错误!");
            return Constants.MEMBER_REGISTER_PAGE;
        }

        // 注册成功,跳转到登陆页面
        return Constants.MEMBER_LOGIN_PAGE;

    }

}
